package com.acmedcare.framework.exchange.center.endpoint.service;

import com.acmedcare.framework.boot.snowflake.Snowflake;
import com.acmedcare.framework.exchange.center.common.ConvertUtils;
import com.acmedcare.framework.exchange.center.common.Page;
import com.acmedcare.framework.exchange.center.endpoint.exception.InvalidRequestParameterException;
import com.acmedcare.framework.exchange.center.entity.bean.Consumer;
import com.acmedcare.framework.exchange.center.entity.bean.PluginStatusEnum;
import com.acmedcare.framework.exchange.center.entity.dto.ConsumerDto;
import com.acmedcare.framework.exchange.center.entity.dto.ConsumerQueryDto;
import com.acmedcare.framework.exchange.center.repository.ConsumerRepository;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

@Service
public class ConsumerService {

  final ConsumerRepository repository;
  final Snowflake snowflake;

  public ConsumerService(
      ConsumerRepository repository, Snowflake snowflake) {
    this.repository = repository;
    this.snowflake = snowflake;
  }

  public Page<Consumer> get(ConsumerQueryDto queryDto) {

    PageHelper.startPage(queryDto.getCurrPage(), queryDto.getSize());
    QueryWrapper<Consumer> queryWrapper = new QueryWrapper<>();
    if (!StringUtils.isEmpty(queryDto.getName())) {

      queryWrapper.eq("name", queryDto.getName());
    }
    return ConvertUtils.convertPage(repository.selectList(queryWrapper));
  }

  public void post(ConsumerDto consumerDto) throws InvalidRequestParameterException {

    ConsumerQueryDto queryDto = new ConsumerQueryDto();
    queryDto.setName(consumerDto.getName());
    if (!get(queryDto).getList().isEmpty()) {

      throw new InvalidRequestParameterException("消费者名字已经存在不允许重复");
    }

    Consumer consumer = ConvertUtils.convertType(consumerDto, Consumer.class);
    consumer.setStatus(PluginStatusEnum.UNLOAD);
    consumer.setConsumerId(snowflake.nextId());
    repository.insert(consumer);
  }

  public void put(ConsumerDto consumerDto, Long id) throws InvalidRequestParameterException {

    ConsumerQueryDto queryDto = new ConsumerQueryDto();
    queryDto.setName(consumerDto.getName());

    Page<Consumer> consumers = get(queryDto);
    if (!consumers.getList().isEmpty()) {

      if (!consumers.getList().get(0).getConsumerId().equals(id)) {

        throw new InvalidRequestParameterException("消费者名字不允许重复！");
      }
    }

    Consumer consumer = ConvertUtils.convertType(consumerDto, Consumer.class);
    consumer.setConsumerId(id);
    repository.updateById(consumer);
  }

  public void delete(Long id) {

    repository.deleteById(id);
  }

  public Consumer getById(Long id) {

    return repository.selectById(id);
  }

  public void update(Consumer consumer) {

    repository.updateById(consumer);
  }
}
